<?php

if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * paymentOffice controller
 * @author Phuc Nguyen - 09/03/2015
 * http://www.facebook.com/phucthuong
 * email : nguyenvanphuc0626@gmail.com
*/
class paymentOffice extends BACKEND_Controller {

	public function __construct() {
		parent::__construct();
		$this->load->language('paymentOffice');
		$this->load->language('button');
		if($this->database_connect_status){
			$this->load->model('paymentOffice_model');
			$this->set_controller('paymentOffice');
			$this->set_model($this->paymentOffice_model);
		}
                $this->load->model('user_model');
                $this->load->library('bookinglib');
                $this->bookinglib = new bookinglib();
	}
        
        public function ajaxAutoload(){
             $ajax = $this->paymentOffice_model->getInfoAjax();
             if($ajax[0]->count > 0){
                 $this->view_data['ajax'] = $ajax;
                 $this->load->view('auth/paymentOffice/ajaxAutoload', $this->view_data);
             }
        }
        
       protected function update($params=NULL){
                $this->bookinglib->direct();
		if($this->input->server('REQUEST_METHOD')=='POST'){
                        $this->view_data["paymentOffice"]                                 = new stdClass();
                        $this->view_data["paymentOffice"]->surplus                          = $this->input->post('surplus');
                        $this->view_data["paymentOffice"]->thucnhan                         = $this->input->post('thucnhan');
                        $this->view_data["paymentOffice"]->amount                           = $this->input->post('thucluu');
                        $this->view_data["paymentOffice"]->residual                         = $this->input->post('residual');
                        
                        $this->view_data["paymentOffice"]->note                           = $this->input->post('note');
                        $this->view_data["paymentOffice"]->payment_confirm                = 1;
                        $this->view_data["paymentOffice"]->agent_code                     = $this->session->userdata['agent_code'];
                        $this->view_data["paymentOffice"]->lastupdated                    = time();
                        
                        $this->load->helper('form');
                        $this->load->helper('character');
                        $this->load->helper('form');
                        $this->load->library('form_validation');
                        $this->form_validation->set_error_delimiters('<div class="alert alert-error"><strong>'.$this->lang->line('error').': </strong>', '</div>');
                        $rules = array(
                            array(
                                'field'   => 'thucnhan',
                                'label'   =>  $this->lang->line('thucnhan'),
                                'rules'   => 'required|numberic|max_length[10]|xss_clean'
                            ),array(
                                'field'   => 'thucluu',
                                'label'   =>  $this->lang->line('thucluu'),
                                'rules'   => 'required|numberic|max_length[10]|xss_clean'
                            ),array(
                                'field'   => 'note',
                                'label'   =>  $this->lang->line('note'),
                                'rules'   => 'required|trim|max_length[255]|xss_clean'
                            )
                        );

                        $this->form_validation->set_error_delimiters('<div class="alert alert-error"><strong>'.$this->lang->line('error').': </strong>', '</div>');
                        $this->form_validation->set_rules($rules);

                        if ($this->form_validation->run()==TRUE){
                            if(isset($params) && $params){
                                 //edit data
                                $this->paymentOffice_model->update($this->view_data["paymentOffice"], $params);
                                $logAction                     = $this->lang->line('update_paymentOffice_success').$params;
                            }

                            /*
                             * insert log payment
                             */
                            unset($this->view_data["paymentOffice"]->payment_confirm);
                            $this->view_data["paymentOffice"]->customerID       =   $this->input->post('customerID');
                            $this->view_data["paymentOffice"]->booking_id       =   $this->input->post('booking_id');
                            $this->view_data["paymentOffice"]->note             =   $this->input->post('payment').' '.$this->input->post('note');
                            $this->view_data["paymentOffice"]->owner            = $this->session->userdata['user_id'];
                            
                            $this->load->model('paymentlog_model');
                            $this->paymentlog_model->create($this->view_data["paymentOffice"]);
                            /*
                             * update list booking
                             */
                            $this->load->model('booking_model');
                            $data = array(
                                'customerID'=>$this->view_data["paymentOffice"]->customerID,
                                'booking_id'=>$this->input->post('booking_id'),
                                'amount'=>$this->view_data["paymentOffice"]->amount
                            );
                            $this->booking_model->udpate_confirm($data);
                            unset($this->view_data["paymentOffice"]);
                            
                            /*
                             * update danh ba KH
                             */
                            $this->load->model('listcustomers_model');
                            $this->listcustomers_model->updateSurplusChung($this->input->post('customerID'),$this->input->post('residual'));
                            
                            //trường hợp tạm ứng : đồng ý
                            if($this->input->post('advance') == 1){
                                $this->listcustomers_model->updateMoneyTotal($this->input->post('customerID'),$this->input->post('thucluu'),date('Y-m-d H:i:s',time()));
                                $this->controlAd($this->input->post('booking_id'));
                                $this->logBookStatitics($this->input->post('booker'));
                            }
                            //trường hợp tạm ứng : đồng ý
                            
                            if($params){
                                    $this->session->set_flashdata('flash_message', $this->lang->line('update_successful'));
                                    $paramAdminLog  = array(
                                        'userid'            => $this->session->userdata['user_id'],
                                        'lastLogin'         => date('Y-m-d :H:i:s',time()),
                                        'ip'                => $_SERVER['REMOTE_ADDR'],
                                        'logAction'         => $logAction,
                                        'agent_code'        => $this->session->userdata['agent_code']
                                    );
                                    $this->user_model->insertUserAdminLog($paramAdminLog);

                                    redirect('auth/paymentOffice');
                            }
                        }
            }
            
            $this->load->model('paymentOffice_model');
            $this->load->model('language_model');

            if(isset($params)){
                    $paymentOffice_query	= $this->paymentOffice_model->find_by(array('id' => $params));
                    
                    if(!isset($paymentOffice_query[0])){
                            $this->session->set_flashdata('flash_message', $this->lang->line('not_exists'));
                            redirect(site_url('auth/paymentOffice'));
                            exit();
                    }

                    $this->view_data['paymentOffice']				= $paymentOffice_query[0];
            }

            $this->view_data['js'] = array(
                            base_url().'static/templates/backend/js/main.js'
            );
            $this->view_data['css'] = array(
            );
            $this->load->view('auth/paymentOffice/edit', $this->view_data);
	}
        
        public function controlAd($params){
            
            //update list bookHistory
            $this->load->model('booking_model');
            $info                   = $this->booking_model->find_by(array('id' => $params));

            $ngay_dau_bay           =   json_decode($info[0]->booking);
            $check                  =   explode("-",$ngay_dau_bay[0]);
            $info[0]->ngay_dau_bay  =   date("Y-m-d",strtotime(str_replace('/','-',$check[0])));
            $info[0]->booking_id    =   $this->input->post('booking_id');
            $info[0]->payment_air   =   1;
            if($info[0]->payment_method == 2 && $info[0]->booking_types == 1){
                $agw                    = 0;
                if(strpos($info[0]->booking,'AGW')){
                    $json_booking = json_decode($info[0]->booking);
                    foreach($json_booking as $keys => $values){
                        if(strpos($values,'AGW')){
                            $agw = $agw + 1;
                        }
                    }
                }
                $info[0]->segments      =   (count(json_decode($info[0]->booking)) - $agw) * count(explode("||", $info[0]->booking_customer_name));
            }

            $this->load->model('bookhistory_model');
            unset($info[0]->id);unset($agw);
            $result = $this->bookhistory_model->create($info[0]);
            if(!$result){
                die("Log Booking Fail! Contact Admin!");
            }
            //delete booking
            $this->booking_model->delete(array('id' => $params)); 
            //-----------------------------
            
            /*
             * updated list CSKH
             */
            $info_CSKH                          = $this->listcustomers_model->find_by(array('customerID'=>$info[0]->customerID));

            $l_CSKH                             = new stdClass();
            $l_CSKH->customerID                 = $info[0]->customerID;
            $l_CSKH->name                       = $info_CSKH[0]->name;
            $l_CSKH->phone                      = $info_CSKH[0]->phone;
            $l_CSKH->booking_place_code         = $info[0]->booking_place_code;
            $l_CSKH->airline                    = $info[0]->airline;
            $l_CSKH->ngay_dau_bay               = $info[0]->ngay_dau_bay;
            $l_CSKH->phone_callstatus           = $this->input->post('phone_callstatus');
            $l_CSKH->agent_code                 = $this->session->userdata['agent_code'];
            $l_CSKH->lastupdated                = date("Y-m-d H:i:s",time());

            $this->load->model('flyTomorrow_model');
            $resultFly      = $this->flyTomorrow_model->create($l_CSKH);
            if(!$resultFly){
                die("Update list CSKH fail!COntact Admin!");
            }
            unset($resultFly);
            unset($l_CSKH);
            /*
             * updated list CSKH rate booker
             */
            $r_CSKH                             = new stdClass();
            $r_CSKH->customerID                 = $info[0]->customerID;
            $r_CSKH->name                       = $info_CSKH[0]->name;
            $r_CSKH->phone                      = $info_CSKH[0]->phone;
            $r_CSKH->ngay_dau_bay               = $info[0]->ngay_dau_bay;
            $r_CSKH->booker                     = $info[0]->owner;
            $r_CSKH->real_fare                  = $info[0]->real_fare;
            $r_CSKH->lastupdated                = date("Y-m-d H:i:s",time());
            $this->load->model('customerAssess_model');
            $_resultFly      = $this->customerAssess_model->create($r_CSKH);
            if(!$_resultFly){
                die("Update list CSKH rate booker fail!Contact Admin! update > 162");
            }

            unset($_resultFly);
            unset($r_CSKH);

            /*
             * update money users and ticket
             */
            $this->load->model('ticketWorkers_model');
            $_u_cash_booking    = $this->user_model->updateCashBooking(array('user_id'=>$info[0]->owner));
            if($info[0]->payment_method == 2 && $info[0]->ticket_workers){
               $_t_cash_booking    = $this->ticketWorkers_model->updateCashBooking(array('id'=>$info[0]->ticket_workers)); 
            }
            if(!$_u_cash_booking){
                die("Update list money users-ticket fail!Contact Admin! update > 174");
            }
            unset($_u_cash_booking);unset($_t_cash_booking);
            unset($info_CSKH);
            
            
            //book statictis
            $this->load->model('bookStatistic_model');
            $statistic = array(
                'owner'         => $this->session->userdata['user_id'],
                'lastupdated'   => date("Y-m-d")
            );

            $query = $this->bookStatistic_model->updateStatisticBookOk($statistic);
            if(!$query){
                $this->view_data["statistic"]                   = new stdClass();
                $this->view_data["statistic"]->booking_ok       = 1;
                $this->view_data["statistic"]->owner            = $statistic['owner'];
                $this->view_data["statistic"]->agent_code       = $this->session->userdata['agent_code'];
                $this->view_data["statistic"]->lastupdated      = $statistic['lastupdated'];

                $this->bookStatistic_model->create($this->view_data["statistic"]);
            }
            
        }//public function controlAd($params){
        
        public function logBookStatitics($booker){
            $this->load->model('bookStatistic_model');
            $statistic = array(
                'owner'         => $booker,
                'lastupdated'   => date("Y-m-d")
            );

            $query = $this->bookStatistic_model->updateStatisticBookOk($statistic);
            if(!$query){
                $this->view_data["statistic"]                   = new stdClass();
                $this->view_data["statistic"]->booking_ok       = 1;
                $this->view_data["statistic"]->owner            = $statistic['owner'];
                $this->view_data["statistic"]->agent_code       = $this->session->userdata['agent_code'];
                $this->view_data["statistic"]->lastupdated      = $statistic['lastupdated'];

                $this->bookStatistic_model->create($this->view_data["statistic"]);
            }
        }
}